import cgi
import os
import sys
import logging

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.ext.webapp import template

import yahtzee
import jsonpickle
import simplejson

#import django.utils.simplejson
#sys.modules['simplejson'] = django.utils.simplejson
#jsonpickle.load_backend('django.utils.simplejson', 'dumps', 'loads', ValueError)
#jsonpickle.set_preferred_backend('django.utils.simplejson')


class Game(db.Model):
    """ DiceDice game state """
    user = db.UserProperty(auto_current_user_add=True)
    state = db.TextProperty()
    games_won = db.IntegerProperty()
    games_lost = db.IntegerProperty()


class MainPage(webapp.RequestHandler):
    def post(self):

        action = self.request.get('action')        
        #action = self.request.body
        results = {'success':False}

        errors = []
        debug = {}
        
        #logging.debug("PRINTING ACTION")
        #logging.debug(action)
        
        #action = request.POST.get('action', False)
        if(action == 'roll'):            
            roll_active = True
                             
            ##################
            if users.get_current_user():
                url = users.create_logout_url(self.request.uri)
                url_linktext = 'Logout'
            else:
                url = users.create_login_url(self.request.uri)
                url_linktext = 'Login'
    
            query = Game.all()
    
            user = users.get_current_user()
    
            if user:
                query.filter('user = ', user)
                g = query.fetch(1)
                if not g:
                    g = Game(state=yahtzee.getNewGameJson(), games_won=0, games_lost=0)
                    g.put()
                else:
                    g = g[0]
            ##################
            
                y = jsonpickle.decode(g.state)
                if(y.checkGameContinue()):
                    #y.checkScores()
                    if y.roll_number > 3:
                        roll_active = False
                
                    if y.roll_number == 1:
                        y.rollAllDice()
                        g.state = jsonpickle.encode(y)
                        #i turned saving to database off while I debug javascript json parsing
                        g.put()
                        game_continue = y.checkGameContinue()
                        show_score_form = game_continue and (y.roll_number <> 1)
                        results = {'success':True}
                        results['msg'] = dict(
                                              user=g.user,
                                              info=y.doGameScreen(),
                                              dice=y.diceState(),
                                              scores=y.getScores(),
                                              roll_number = y.roll_number,
                                              roll_active = roll_active,
                                              game_continue = game_continue,
                                              show_score_form=show_score_form,
                                              keep_dice = y.keep_dice
                                              )
                    elif(y.roll_number == 2 or y.roll_number == 3):
                        try:
                            #dice_to_roll_json = request.POST.getlist('dice_to_roll')
                            #dice_to_roll = jsonpickle.decode(dice_to_roll_json) 
                            dice_to_roll = [int(x) for x in self.request.get_all('dice_to_roll')]
                
                        except ValueError, TypeError:
                            results['msg'] = 'You tried to cheat by putting in bad dice index positions!'
                        else:
                            if(dice_to_roll):
                                y.rollDice(dice_to_roll)
                                debug['dice_to_roll'] = dice_to_roll
                                if y.roll_number > 3:     #y.rollDice will increment rollNumber automatically
                                    roll_active = False     #set roll active to false to force user to select scoring category
                                g.state = jsonpickle.encode(y)
                                g.put()
                                game_continue = y.checkGameContinue()
                                show_score_form = game_continue and (y.roll_number <> 1)
                                results = {'success':True}
                                results['msg'] = dict(
                                                      user=g.user,
                                                      info=y.doGameScreen(),
                                                      dice=y.diceState(),
                                                      scores=y.getScores(),
                                                      roll_number = y.roll_number,
                                                      roll_active = roll_active,
                                                      game_continue = game_continue,
                                                      show_score_form=show_score_form,
                                                      keep_dice = y.keep_dice,
                                                      url = url,
                                                      url_linktext = url_linktext
                                                      )
                                #g.save()
                            else:
                                results['msg'] = "You didn't select any dice to roll!"
                    else:
                        #no more rolls left!
                        roll_active = False #weird, since you should never get here!
                        results['msg'] = 'You tried rolling when there were no rolls left for the turn!'
    
                json = jsonpickle.encode(results)
                self.response.headers["Content-Type"] = "application/json"
                return self.response.out.write(json)
            
        elif (action == 'score'):
            scorecat = self.request.get('scorecat', False)
            if scorecat == False:
                results['msg'] = 'No scoring category picked!'
            try:
                ##################
                if users.get_current_user():
                    url = users.create_logout_url(self.request.uri)
                    url_linktext = 'Logout'
                else:
                    url = users.create_login_url(self.request.uri)
                    url_linktext = 'Login'
        
                query = Game.all()
        
                user = users.get_current_user()
        
                g = Game(state=yahtzee.getNewGameJson(), games_won=0, games_lost=0)
                
                if user:
                    query.filter('user = ', user)
                    gq = query.fetch(1)
                    if not gq:
                        #g = Game(state=yahtzee.getNewGameJson(), games_won=0, games_lost=0)
                        g.put()
                    else:
                        g = gq[0]
                else:
                    self.redirect(users.create_login_url(self.request.uri))
                ##################
                y = jsonpickle.decode(g.state)
                y.writeScore(scorecat)
                y.resetRoll()
                roll_active = True
            except KeyError:
               results['msg'] = 'You tried inputting an invalid scoring category!'
            else:
                g.state = jsonpickle.encode(y)
                g.put()
                game_continue = y.checkGameContinue()
                show_score_form = game_continue and (y.roll_number <> 1)
                results = {'success':True}
                results['msg'] = dict(
                                      user = g.user,
                                      info=y.doGameScreen(),
                                      dice=y.diceState(),
                                      scores=y.getScores(),
                                      roll_number = y.roll_number,
                                      roll_active = roll_active,
                                      game_continue = game_continue,
                                      show_score_form=show_score_form,
                                      keep_dice = y.keep_dice,
                                      url = url,
                                      url_linktext = url_linktext
                                      )

            #json = jsonpickle.encode(results)
            #self.response.headers["Content-Type"] = "application/json"
            #return self.response.out.write(json)
            return self.redirect("/")              
        elif action == 'new_game':
            ##################
            query = Game.all()
            user = users.get_current_user()
            if user:
                query.filter('user = ', user)
                g = query.fetch(1)
                if not g:
                    g = Game(state=yahtzee.getNewGameJson(), games_won=0, games_lost=0)
                    g.put()
                else:
                    g = g[0]
                    g.state = yahtzee.getNewGameJson()
                    g.put()
            ##################
            
            return self.redirect('/')
            
    def get(self):
        
        ##################
        if users.get_current_user():
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'
        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Login'

        query = Game.all()

        user = users.get_current_user()
        
        g = Game(state=yahtzee.getNewGameJson(), games_won=0, games_lost=0)
        
        if user:
            query.filter('user = ', user)
            gq = query.fetch(1)
            if not gq:
                #g = Game(state=yahtzee.getNewGameJson(), games_won=0, games_lost=0)
                g.put()
            else:
                g = gq[0]
        else:
            self.redirect(users.create_login_url(self.request.uri))
        ##################
        
        y = jsonpickle.decode(g.state)
        errors = []
        debug = {}
        roll_active = True
    
        game_continue = y.checkGameContinue()
        show_score_form = game_continue and (y.roll_number <> 1)

        if y.roll_number > 3:
            roll_active = False        

        game = dict(
                    user=g.user,
                    info=y.doGameScreen(),
                    dice=y.diceState(),
                    scores=y.getScores(),
                    errors=errors,
                    roll_number = y.roll_number,
                    roll_active = roll_active,
                    game_continue = game_continue,
                    show_score_form=show_score_form,
                    keep_dice = y.keep_dice,
                    url = url,
                    url_linktext = url_linktext
                    )
        debug['game'] = game
        #debug['post'] = self.request.get_all(self.request.arguments())
        debug['post'] = self.request.arguments()
        
        path = os.path.join(os.path.dirname(__file__), 'game_ajax.html')
        self.response.out.write(template.render(path, {'game': game, 'debug': debug, 'action': "get request"}))        
#        if users.get_current_user():
#            url = users.create_logout_url(self.request.uri)
#            url_linktext = 'Logout'
#        else:
#            url = users.create_login_url(self.request.uri)
#            url_linktext = 'Login'
#
#        query = Game.all()
#
#        user = users.get_current_user()
#
#        #template_values = { 'url' : url, 'url_linktext' : url_linktext }
#
#        if user:
#            query.filter('user = ', user)
#            game = query.fetch(1)
#            if not game:
#                game = Game(state=yahtzee.getNewGameJson(), games_won=0, games_lost=0)
#                game.put()
#            else:
#                game = game[0]
#            #template_values['game']= game.state
#           
#        y = jsonpickle.decode(game.state)
#        
#        roll_active = True
#        show_score_form = True
#        game_continue = True
#        debug = {"game.state":game.state, "user" : user }
#        
#        game = dict(
#            debug=debug,
#            url=url, url_linktext=url_linktext, user=user,          
#            info=y.doGameScreen(), dice=y.diceState(),
#            scores=y.getScores(), roll_number = y.roll_number,
#            roll_active = roll_active, game_continue = game_continue,
#            show_score_form=show_score_form, keep_dice = y.keep_dice
#        )
#
#        path = os.path.join(os.path.dirname(__file__), 'game_ajax.html')
#        self.response.out.write(template.render(path, game))

application = webapp.WSGIApplication(
   [('/', MainPage)],
   debug = True
)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()